package com.tjakus.main;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.tjakus.hibernate.HibernateUtil;
import com.tjakus.logging.Logging;
import com.tjakus.properties.Property;
import com.tjakus.quartz.*;

/**
 * This is the servlet context listener which is responsible for initialization
 * and tasks scheduling
 * 
 * @author tjakus
 * 
 */

public class ApplicationInitializerListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {

	}

	/**
	 * This is the method which will be called upon application startup
	 * 
	 */

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		boolean status;

		Logging.getLogger().info("ApplicationInitializerListener - [ STARTED ] ");
		// Initialize and setup connection towards database
		status = HibernateUtil.buildSessionFactory();
		if (!status) {
			Logging
					.getLogger()
					.error(
							"ApplicationInitializerListener - [ HibernateUtil initialization FAILED ] ");
			return;
		}

		// Initialize all properties
		if (!Property.initializeProperties()) {
			Logging
					.getLogger()
					.error(
							"ApplicationInitializerListener - [ Properties initialization FAILED ] ");
			return;
		}

		// Proxy settings for ETK network (not enough for org.apache.http.client)
		if (Property.IS_PROXY_ENABLED.equalsIgnoreCase("TRUE")) {
			System.setProperty("http.proxyHost", Property.PROXY_HOST);
			System.setProperty("http.proxyPort", "" + Property.PROXY_PORT);
		}

		// Initialize quartz jobs
		status = QuartzUtil.initializeQuartzJobs();
		if (status) {
			// Schedule quartz jobs
			QuartzUtil.scheduleJobs();
		}
		Logging.getLogger().info(
				"ApplicationInitializerListener - [ FINISHED SUCCESSFULLY ] ");
	}
}
